<template>
  <div id="userLayout" :class="['user-layout-wrapper']">
    <div class="top">
      <div class="header">
        <a href="#">
          <img :src="oemSiteInfo.sysLogoUrl" style="height: 99px;">
        </a>
      </div>
    </div>
    <div class="tip">
      <div class="text big">欢迎登录</div>
      <div class="text">Welcom to login</div>
      <div class="line" />
    </div>
    <div class="container" :style="[{background: 'url(' + oemSiteInfo.mgr.loginPageBGImgUrl + ')'}, {backgroundSize:'cover' }, {backgroundPosition: 'center top'}, {backgroundRepeat:'no-repeat'}]">
      <div class="user-layout-lang" />
      <div class="user-layout-content">
        <!-- 错误提示信息 -->
        
        <div class="main">
          <a-alert
            v-if="showLoginErrorInfo"
            type="error"
            banner
            showIcon
            style="margin-bottom: 24px;"
            :message="showLoginErrorInfo"
          />
          <div class="desc">
            营销运营平台
          </div>
          <a-form ref="formLogin" class="user-layout-login" :model="formState" :rules="loginrules" @submit="handleSubmit">
            <a-form-item name="username" class="input-item">
              <login-text-up v-model:value="formState.username" :disabled="!vdata.googleIsShow" :isLogin="true" :placeholder="vdata.googleIsShow?'手机号':''" />
            </a-form-item>

            <a-form-item name="password" class="input-item" style="margin-bottom: -20px !important">
              <login-text-up v-model:value="formState.password" :disabled="!vdata.googleIsShow" :isLogin="true" :placeholder="vdata.googleIsShow?'密码':''" isPassword="password" />
            </a-form-item>

            <div class="code-body">
              <div class="code-layout" :class="{ googleShow: !vdata.googleIsShow }">
                <div class="code code-layout-item">
                  <a-form-item name="vercode" class="input-item">
                    <login-text-up v-model:value="formState.vercode" :isLogin="true" placeholder="短信验证码" />
                  </a-form-item>
                  <div>
                    <a-button :loading="smsConfig.isSendLoading" :disabled="smsConfig.isSend" type="primary" style="height: 40px;margin-left: 10px" @click="sendCode">{{ smsConfig.tip }}</a-button>
                  </div>
                </div>
                <!-- <a-form-item name="mfaCode" class="input-item">
                  <login-text-up
                    v-model:value="formState.mfaCode"
                    style="width: 300px"
                    placeholder="安全码"
                    :isLogin="true"
                    :isGoogle="'false'"
                    class="code-layout-item"
                  />
                </a-form-item> -->
              </div>
            </div>
            <!-- <a-tag v-if="!vdata.googleIsShow" color="orange">您已开启虚拟MFA验证，请输入MFA动态安全码。</a-tag> -->
            <!-- <a-form-item style="margin-bottom: 30px;">
              <!== 自动登录 ==>
              <!== <a-checkbox v-model:checked="isAutoLogin">自动登录</a-checkbox> ==>
              <!== 忘记密码 ==>
              <!== <a class="forge-password" style="float: right;" @click="toForgetPwd">忘记密码?</a> ==>
            </a-form-item> -->
          </a-form>
          <a-button
            size="large"
            type="primary"
            :loading="loginBtnLoadingFlag"
            style="width: 300px"
            @click="handleSubmit"
          >
            {{ vdata.submitText }}
          </a-button>
        </div>
        <div class="footer" />
      </div>
    </div>
    <!-- <div class="bottom"> 郑州一鑫信息技术有限公司  <a href="https://beian.miit.gov.cn" target="_blank" style="margin-left: 10px;"> 豫ICP备2022018968号 </a> </div> -->
  </div>
</template>
<script setup lang="ts">
import { timeFix } from '@/utils/util'
import { vercode } from '@/api/login'
import { login } from '@/api/login'
import { useUserStore } from '@/store/modules/user'
import { API_URL_PROXY_LIST, req, $queryOrgTree, API_URL_SYS_SMS_SEND_MSG } from '@/api/manage'
import { useOem } from '@/store/modules/oem'
import router from '@/router'
import {ref, onMounted, reactive, getCurrentInstance, h,onUnmounted} from 'vue'

// 获取全局函数
const { $infoBox } = getCurrentInstance()!.appContext.config.globalProperties

const vdata = reactive({
  googleIsShow: true, // 是否让谷歌输入框展示
  submitText: '登录' ,
})

const userStore = useUserStore()

// 获取网站信息
const oemSiteInfo = useOem().getSiteInfo()

let loginPosition = ref('') // 决定登录框水平位置 左中右？
let loginPageCardPosition = oemSiteInfo.mgr.loginPageCardPosition
if(loginPageCardPosition === 'right') {
  loginPosition.value = 'flex-end'
} else if (loginPageCardPosition === 'center') {
  loginPosition.value = 'center'
} else if (loginPageCardPosition === 'left') {
  loginPosition.value = 'flex-start'  
}


let isOverdue = ref(false)  // 设置过期样式
let isAutoLogin = ref()  // 是否是自动登录
let loginBtnLoadingFlag = ref(false)  // 登录按钮是否显示 加载状态
let showLoginErrorInfo = ref('')  // 是否显示登录错误面板信息
let timer: number = -1
let vercodeImgSrc = ref('')  // 验证码图片
let vercodeToken = ref('') // 验证码验证token

let formLogin = ref()

let formState = reactive({
  username: '',
  password: '',
  vercode: '',
  mfaCode: ''
} as any)
const loginrules: any = reactive({
  username: [
        { required: true, pattern: /^[1][0-9]{10}$/, message: '请输入正确的手机号码', trigger: 'blur' },
      ],
  password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
      ],
  vercode: [
        { required: true, message: '请输入验证码', trigger: 'blur' },
        { max: 6, message: '验证码长度错误', trigger: 'blur' }
      ],
})
// 验证码相关配置
const smsConfig = reactive({
  tip: '发送短信验证码', // 验证码提示文字
  count: 60, // 倒计时
  timer: null, // 计时器
  code: '', // 验证码
  isSend: false, // 是否发送验证码
  isSendLoading: false, // 发送验证码按钮loading
} as any)

/**
 * 发送验证码
 */
async function sendCode(){
  // 校验手机号
  await formLogin.value.validate(['username'])
  smsConfig.isSendLoading = true
  // 获取验证码
  req.add(API_URL_SYS_SMS_SEND_MSG, { phone: formState.username, flag: 0 }).then(res => {
    smsConfig.isSendLoading = false
    smsConfig.isSend = true
    smsConfig.tip = `${smsConfig.count}秒后重新发送`
    $infoBox.message.success('验证码发送成功,请注意查收')
    smsConfig.timer = setInterval(() => {
      if(smsConfig.count <= 0){
        smsConfig.isSend = false
        smsConfig.tip = '发送短信验证码'
        smsConfig.count = 60
        clearInterval(smsConfig.timer)
        return
      }
      smsConfig.tip = `${smsConfig.count}秒后重新发送`
      smsConfig.count--
    },1000)
  }).catch(() => {
    smsConfig.isSendLoading = false
  })
}


 // handler
function handleSubmit () {
  let loginParams = {
    username: formState.username,
    password: formState.password,
    vercode: formState.vercode,
    vercodeToken: vercodeToken.value,
    googleCode: formState.mfaCode,
  }

  formLogin.value.validate().then(() => {
    loginBtnLoadingFlag.value = true // 登录按钮显示加载loading
    // 请求登录
    login(loginParams).then((bizData) => {
      showLoginErrorInfo.value = ''
      loginBtnLoadingFlag.value = false

      userStore.putToken(bizData['iToken'])

      router.push({ path: '/' })
      // 延迟 1 秒显示欢迎信息
      setTimeout(() => {
        let lastLoginTimeStr = bizData['lastLoginTime'] ? '上次登录时间：' + bizData['lastLoginTime'] : ''
        $infoBox.notification.success({message: '欢迎', description: [h('p', `${timeFix()}，欢迎回来`), h('p', lastLoginTimeStr)] })

      }, 1000)
      showLoginErrorInfo.value = ''

      // router.push('/merchant/list')
    }).catch( err => {
      console.log('err',err)
      loginBtnLoadingFlag.value = false
      showLoginErrorInfo.value = (err.msg || JSON.stringify(err))
      // 延迟 1 秒跳转修改密码页面
      if(err.code == 5006){
        setTimeout(()=>{
          router.push({ name: 'forget', path: '/user/forget' })
        },1000)
      }
    })
  })
  .catch(error => {
    console.log('error', error)
  })
}

// 忘记密码跳转页面
function toForgetPwd () {
  router.push({ name: 'forget', path: '/user/forget' })
}

// 监听回车事件  
document.onkeydown = function (e) {
    var theEvent = e || window.event    
    var code = theEvent.keyCode || theEvent.which || theEvent.charCode 
    if (code == 13) { //回车键的键值为13
      handleSubmit()
    }
}
onUnmounted(() =>{
  document.onkeydown = null
})
</script>

<style lang="less" scoped>

#userLayout.user-layout-wrapper {
  height: 100%;
  .top {
    position: absolute;
    z-index: 11;
    top: 90px;
    left:90px;
    height: 80px;
    // padding: 0 35px;
    box-sizing: border-box;
    display: flex;
    justify-content: space-between;
    // align-items: center;
    align-items: normal;
    .header {
      height: 44px;
      line-height: 44px;
    }

    .bi{
      font-size: 18px;
    }
  }
  .tip{
    position: absolute;
    z-index: 11;
    bottom: 90px;
    left:90px;
    color: #fff;
    font-family: AlibabaPuHuiTi-Regular;
    font-size: 24px;
    font-weight: 200;
    .big{
      font-weight: 400;
      font-size: 64px;
    }
    .line{
      width: 120px;
      height: 4px;
      background: #fff;
      margin-top: 70px;
    }
  }
  .container {
    display: flex;
    justify-content: center;
    align-items: center; //修改这一项来决定登录对话框的水平位置，flex-start == left； center == center； flex-end == right
    flex-direction: column;
    box-sizing: border-box;
    padding: 0;
    width: 100%;
    // height: calc(100vh - 80px);
    height: calc(100vh);
    min-height: 700px;
    background: #f0f2f5 url(/src/assets/svg/background.svg) no-repeat 50%;
    background-size: cover;
    //padding: 50px 0 84px;
    position: relative;
    transition: 0.3s ease;

    .user-layout-lang {
      width: 100%;
      // height: 40px;
      // line-height: 44px;
      height: 0;
      text-align: right;
    }

    .user-layout-content {
      width: 100%;
      height: 100vh;
      transition: 0.3s ease;
       input {
          height: 40px !important;
        }

      .main {
        padding: 50px 30px;
        box-sizing: border-box;
        width: 100%;
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: flex-start;
        // background: #fff;
        // border-top: 1px solid #e7eaf3;
        align-items: center;
        transition: all 0.3s , border 0s ease;
        background: rgba(0, 0, 0, 0.45);
        backdrop-filter: blur(15px);
        .ant-form{
          max-width: 300px;
        }
        .desc {
          font-weight: bold;
          font-size: 36px;
          letter-spacing: 0.04em;
          // color: @primary-color;
          color:#fff;
          margin-bottom: 50px;
          text-align: center;
        }
        .input-item {
          height: 65px;
          margin:0 !important;
        }
        .ant-checkbox-wrapper{
          color: #fff;
        }
      }

      .footer {
        // position: absolute;
        width: 100%;
        bottom: 0;
        padding: 0 16px;
        margin: 48px 0 24px;
        text-align: center;

        .links {
          margin-bottom: 8px;
          font-size: 14px;
          a {
            color: rgba(0, 0, 0, 0.45);
            transition: all 0.3s;
            &:not(:last-child) {
              margin-right: 40px;
            }
          }
        }
        .copyright {
          color: rgba(0, 0, 0, 0.45);
          font-size: 14px;
        }
      }
    }

    a {
      text-decoration: none;
    }

  }
  
  //登录页响应式的调整
  @media screen and (min-width:769px) and (max-width:1024px){
    @topTipM:50px;
    .tip{
      font-size: 14px;
      .big{
        font-size: 36px;
      }
      .line{
        margin-top: 30px;
      }
    }
    .container {
      // padding: 0 100px;
      // min-height: 700px;
      // height: calc(100vh - 80px);
      align-items: v-bind(loginPosition);
      .user-layout-content {
        width: 38%;
        min-width: 360px;
        // height: auto;
        .main{
          // width: 360px;
          box-shadow: 0 6px 12px rgb(140 152 164 / 8%);
          // border: 0.0625rem solid #E7EAF3 ;
          // height: auto;
          justify-content: center;
          // border-radius: 10px;
        }
      }
    }
  }
  @media screen and (min-width:1025px) and (max-width:1366px){
    .container {
      // padding: 0 150px;
      // min-height: 700px;
      // height: calc(100vh - 80px);
      align-items: v-bind(loginPosition);
      .user-layout-content {
        width: 38%;
        min-width: 360px;
        // height: auto;
        .main{
          // width: 360px;
          box-shadow: 0 6px 12px rgb(140 152 164 / 8%);
          // border: 0.0625rem solid #E7EAF3 ;
          // height: auto;
          justify-content: center;
          // border-radius: 10px;
        }
      }
    }
  }
  @media screen and (min-width:1367px) and (max-width:1600px){
    .container {
      // padding: 0 250px;
      // min-height: 700px;
      // height: calc(100vh - 80px);
      align-items: v-bind(loginPosition);
      .user-layout-content {
        width: 38%;
        min-width: 360px;
        // height: auto;
        .main{
          // width: 360px;
          box-shadow: 0 6px 12px rgb(140 152 164 / 8%);
          // border: 0.0625rem solid #E7EAF3 ;
          // height: auto;
          justify-content: center;
          // border-radius: 10px;
        }
      }
    }
  }
  @media screen and (min-width:1601px){
    .container {
      // padding: 0 300px;
      // min-height: 700px;
      // height: calc(100vh - 80px);
      align-items: v-bind(loginPosition);
      .user-layout-content {
        width: 38%;
        min-width: 360px;
        // height: auto;
        .main{
          // width: 360px;
          box-shadow: 0 6px 12px rgb(140 152 164 / 8%);
          // border: 0.0625rem solid #E7EAF3 ;
          // height: auto;
          justify-content: center;
          // border-radius: 10px;
        }
      }
    }
  }
}

.code-body {
  padding-top: 20px;
  width: 300px;
  overflow-x: hidden;
}
.code-layout {
  display: flex;
  width: 600px;
  transition: .3s;
  .code-layout-item {
    width: 50%;
  }
}
.googleShow {
  margin-left: -300px;
}

</style>

<style lang="less" scoped>
/deep/ input:-webkit-autofill{
  box-shadow: inset 0 0 0 1000px #fff;
}
/deep/ input:hover:-webkit-autofill{
  box-shadow: inset 0 0 0 1000px #fff;
}

.user-layout-login {
 
  label {
    font-size: 14px;
  }

  .forge-password {
    font-size: 14px;
    // color: @gz-theme;
    color: #fff;
  }

  // button.login-button {
  //   padding: 0 15px;
  //   font-size: 16px;
  //   height: 40px;
  //   width: 100%;
  // }

  .user-login-other {
    text-align: left;
    margin-top: 24px;
    line-height: 22px;

    .item-icon {
      font-size: 24px;
      color: rgba(0, 0, 0, 0.2);
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: #1890ff;
      }
    }

    .register {
      float: right;
    }
  }
  .code {
    display: flex;
    justify-content: space-between;
    .code-input {
      width: 216px;
    }
    .code-img {
      width: 120px;
      height: 40px;
      background-color: #ddd;
      margin-left: 10px;
      img{
        width: 120px;
        height: 40px;
      }
    }
  }
  .submit {
    margin-bottom: 0;
  }
}
.vercode-mask {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: #000;
  opacity: 0.8;
  text-align:center;
  line-height: 40px;
  color:#fff;
  &:hover {
    cursor: pointer;
  }
}

a{
		text-decoration: none;
		color: #666666;
		}

		.bottom {
			position: absolute;
			bottom: 0;
			width: 100%;
			background-color: #eeeeee;
			text-align: center;
			line-height: 35px;
			font-size: .8125rem;
			color: #666666;
		}
</style>
